package model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

import model.pieces.Piece;
import model.pieces.Target;
import resources.PieceSymbols;

public class LevelReader {

	private ArrayList<Piece> pieces;
	private String name;

	public LevelReader(URL path) {
		this.pieces = new ArrayList<Piece>();
		this.read(path);
	}

	/**
	 * @return the pieces
	 */
	public ArrayList<Piece> getPieces() {
		return pieces;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	public void read(URL path) {
		try {
			InputStreamReader file = new InputStreamReader(path.openStream());
			try {
				BufferedReader reader = new BufferedReader(file);
				try {
					this.name = readName(reader);
					this.readBoard(reader);
				} finally {
					reader.close();
				}
			} finally {
				file.close();
			}
		} catch (IOException e) {
			System.out.println("Exception throwed while level creation.");
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

	private static String readName(BufferedReader reader) throws IOException {
		String line = reader.readLine();
		if (line == null)
			throw new IOException("no existe el nombre del nivel");
		return line;
	}

	private void readBoard(BufferedReader reader) throws IOException {
		String line;
		int row = 0;
		while ((line = reader.readLine()) != null) {
			this.processLine(line, row);
			row++;
		}
	}

	private void processLine(String line, int row) {
		for (int col = 0; col < line.length(); col++) {
			addPiece(line.charAt(col), row, col);
		}
	}
	
	private void addPiece(Character charAt, int row, int col) {
		Piece piece = PieceFactory.createPiece(charAt, row, col);
		if (piece != null) {
			this.pieces.add(piece);
			addPieceOnTarget(charAt, row, col);
		}
	}
	
	private void addPieceOnTarget(Character charAt, int row, int col) {
		Piece piece;
		switch (charAt) {
		case PieceSymbols.cajaEnDestino:
			// cambiar el estado de Target a ocupado por Box
			piece = PieceFactory.createPiece(PieceSymbols.destino, row, col);
			((Target) piece).setBoxOnTargetState();
			this.pieces.add(piece);
		case PieceSymbols.hombreEnDestino:
			// cambiar el estado de Target a ocupado por Man
			piece = PieceFactory.createPiece(PieceSymbols.destino, row, col);
			((Target) piece).setManOnTargetState();
			this.pieces.add(piece);
			break;
		default:
			break;
		}
	}
}
